import { getCartProductList } from '@/api/shop'
import { updateUserAddress } from '@/api/user'

const shop = {
  state: {
    cartProductData: null,
    addressId: '',
    cartNum: 0,
    orderState: 0
  },
  mutations: {
    SET_CARTPRODUCT_DATA(state, cartProductData) {
      state.cartProductData = cartProductData
    },
    SET_ADDRESS_ID(state, data) {
      state.addressId = data
    },
    SET_CART_NUM(state, data) {
      state.cartNum = data
    },
    SET_ORDER_STATUS(state, data) {
      state.orderState = data
    }
  },
  actions: {
    // 获取购物车信息
    getCartProductList({ commit, state }, parameterData) {
      return new Promise((resolve, reject) => {
        getCartProductList(parameterData)
          .then(response => {
            commit('SET_CARTPRODUCT_DATA', response)
            resolve(response)
          })
          .catch(error => {
            reject(error)
          })
      })
    },
    // 获取购物车数量
    getCartNum({ commit, state }, parameterData) {
      return new Promise((resolve, reject) => {
        getCartProductList(parameterData)
          .then(response => {
            let cartNum = 0
            response.data.cartList.forEach(item => {
              item.goodsList.forEach(good => {
                good.sizeList.forEach(size => {
                  cartNum += size.cartNum
                })
              })
            })
            commit('SET_CART_NUM', cartNum)
            resolve()
          })
          .catch(error => {
            reject(error)
          })
      })
    },
    // 获取购物车数量
    addCartNum({ commit, state }, parameterData) {
      commit('SET_CART_NUM', parameterData)
    },

    // 添加/更新地址
    UpdateUserAddress({ commit, state }, parameterData) {
      return new Promise((resolve, reject) => {
        updateUserAddress(parameterData)
          .then(response => {
            commit('SET_ADDRESS_ID', response.data.addressId)
            resolve(response)
          })
          .catch(error => {
            reject(error)
          })
      })
    },
    // 保存订单状态
    SetOrderStatus({ commit, state }, data) {
      commit('SET_ORDER_STATUS', data)
    }
  }
}

export default shop
